const sequelize = require('../../../../mysql/init');

const {  DataTypes } = require('sequelize');
const  ArchivesModule =  require('./archivesModule.js')
const articlesModule = sequelize.define('articles',{
    id:{
        type:DataTypes.INTEGER,
        primaryKey:true,
        autoIncrement:true
    },
    title:{
        type:DataTypes.STRING,
        unique:true,
        allowNull:false
    },
    content:{
        type:DataTypes.TEXT,
        allowNull:false
    },
    cover:{
        type:DataTypes.STRING,
        allowNull:true
    },
    status:{
        type:DataTypes.STRING,
        allowNull:false,
        defaultValue:'publish'
    },
    category_id:{
        foreignKey:true,
        type:DataTypes.INTEGER,
        allowNull:false
    }   
},{
    freezeTableName:true,
})
//添加触发器当添加新文章时归档tables自动写入数据
articlesModule.afterCreate(async(articles, options) => {
    const {createdAt,title,id} =articles
    const year = createdAt.getFullYear()
    const month = createdAt.getMonth() + 1
    const article_title = title
    const article_id = id
  await ArchivesModule.upsert({
    year,
    month,
    article_title,
    article_id,
  },{
    fields:['year','month','article_title','article_id']
  })
})
module.exports =articlesModule
